using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization;

using Pegasus.Resources;
using Pegasus.Runtime.Serialization.Formatters.Xml;

namespace Pegasus.UnitTests.Runtime.Serialization.Formatters.Xml.XmlFormatter2Tests
{
	/// <summary>
	/// Class holds const and static helper methods that are used by the XmlFormatter2 test classes.
	/// </summary>
	public static class XmlFormatter2Helper
	{
		// Local Static Values
		private static EmbeddedResource s_res = new EmbeddedResource( typeof( XmlFormatter2Helper ).Assembly, "Pegasus.UnitTests.EmbeddedResouces" );
		
		// Local Const Values
		public const int TestLoops = 100;

		// Create a string with some unicode chars in it to make sure the encoding is correctlly handled.
		public const string StringTestValue = "TestStringValue<\u03B1\u03A9>";
		public const int IntTestValue = -105;


		/// <summary>
		/// Gets the embedded resouce manager.
		/// </summary>
		/// <value>The embedded resouces.</value>
		public static EmbeddedResource EmbeddedResouces
		{
			get
			{
				return s_res;
			}
		}

		/// <summary>
		/// Serializes the deserialize.
		/// </summary>
		/// <param name="obj">The obj.</param>
		/// <returns></returns>
		public static object SerializeDeserialize( object obj )
		{
			return SerializeDeserialize( obj, null, new StreamingContext( StreamingContextStates.Persistence ) );
		}

		/// <summary>
		/// Serializes the deserialize.
		/// </summary>
		/// <param name="obj">The obj.</param>
		/// <param name="selector">The selector.</param>
		/// <param name="context">The context.</param>
		/// <returns></returns>
		public static object SerializeDeserialize( object obj, SurrogateSelector selector, StreamingContext context )
		{
			byte[] buffer;

			// Serialize the object out to the buffer.
			using( MemoryStream memStream = new MemoryStream() )
			{
				XmlFormatter2 xmlFormatter = new XmlFormatter2( selector, context );
				xmlFormatter.Serialize( memStream, obj );
				buffer = memStream.GetBuffer();
			}

			// Just here for debugging
			string xml = Encoding.UTF8.GetString( buffer );

			// Deserialize the buffer back to an object
			using( MemoryStream memStream = new MemoryStream( buffer ) )
			{
				XmlFormatter2 xmlFormatter = new XmlFormatter2( selector, context );
				return xmlFormatter.Deserialize( memStream );
			}
		}
	}
}
